<template>
  <div class="addMaintainPlan zy-content">
    <back-level :goPage="back" />
    <Card :title="!editId ? '新增点检计划' :'编辑点检计划'"
      class="detail-content-layout">
      <div class="line-title">
        <Steps :current="current" class="steps">
          <Step title="选择点检对象"></Step>
          <Step title="添加点检内容"></Step>
          <Step title="创建点检时间"></Step>
        </Steps>
      </div>
      <!-- 第一步 -->
      <div class="searchBox" v-if="current === 0">
        <Form class="search-form" ref="stepOneValidate" :rules="stepOneRuleValidate" :model="formInline">
          <div class="labelTop">
            <FormItem label="点检计划" class="item " prop="planName">
              <Input type="text" v-model="formInline.planName" @on-change="planNamechange"
                :placeholder="`${$t('common.inputInfo')}`" clearable class="inputBorder" :maxlength="100"></Input>
            </FormItem>
          </div>
        </Form>
        <div class="addDev" @click="addDev">
          <Icon type="md-add-circle" size="20" />
          添加模具
        </div>
        <div class="tableContent">
          <Table border class="resizable-table" @on-column-width-resize="onColumnWidthResize" :columns="columns"
            :data="data">
            <template slot-scope="{ row }" slot="action">
              <span class="operationBtn" @click="deleteDevRow(row)">{{ $t('common.Delete') }}</span>
            </template>
          </Table>
        </div>
        <Modal :mask-closable="false" v-model="addDevVisible" title="添加模具" width="1400" class="addDevModal modal-content-layout">
          <Form class="search-form" label-position="top">
            <div class="label">
              <FormItem label="功能位置" class="item mr16">
                <Cascader clearable :data="orgList" @on-change="handleCasChangeOne"
                  v-model="searchParams.functionalLocationName" :placeholder="`${$t('common.selectInfo')}`"
                  change-on-select></Cascader>
              </FormItem>
              <FormItem label="模具编号" class="item mr16">
                <Input type="text" v-model="searchParams.moldCode" :placeholder="`${$t('common.inputInfo')}`"
                  class="inputBorder" :maxlength="32"></Input>
              </FormItem>
              <FormItem label="模具名称" class="item mr16">
                <Input type="text" v-model="searchParams.moldName" :placeholder="`${$t('common.inputInfo')}`"
                  class="inputBorder" :maxlength="32"></Input>
              </FormItem>
              <FormItem label="" class="item">
                <Button style="position: relative;top:11px;" class="ivu-btn-lg" type="primary" @click="changeNum">
                  {{ $t('common.Query') }}
                </Button>
              </FormItem>
            </div>
          </Form>
          <div>
            <Table border height="540" class="resizable-table" @on-column-width-resize="onColumnWidthResize" ref="devSelection"
              :columns="addDevcolumns" :data="addDevdata" @on-selection-change="handleSelectionChange"></Table>
            <div class="pageWrap mt16">
              <pageLeftTitle :total="addDevpageParams.total" :selected="selectData.length" />
              <Page :total="addDevpageParams.total" :page-size="addDevpageParams.pageSize"
                :page-size-opts="pageSizeOption" :current="addDevpageParams.pageNum" @on-change="changePageNum"
                @on-page-size-change="changePageSize" show-sizer show-total />
            </div>
          </div>
          <div slot="footer">
            <Button type="default" @click="addDevCancel">{{ $t('common.Cancle') }}</Button>
            <Button type="primary" @click="addDevOk">{{ $t('maintenance.Confirmed') }}</Button>
          </div>
        </Modal>
      </div>
      <!-- 第二步 -->
      <div v-if="current === 1" class="third searchBox" key="2">
        <div class="addPlan" @click="addPlan">
          <Icon type="md-add-circle" size="20" />
          添加点检内容
        </div>
        <div class="tableContent">
          <Table border class="resizable-table" @on-column-width-resize="onColumnWidthResize" ref="selection"
            :columns="contentColumns" :data="contentData">
            <template slot-scope="{ row }" slot="action">
              <span class="operationBtn" @click="deleteRow(row)">{{ $t('common.Delete') }}</span>
            </template>
          </Table>
        </div>
        <Modal :mask-closable="false" v-model="visible" :title="`${$t('common.Detail')}`" class="checkContentModal" width='1200' footer-hide>
          <contentDetail :formInline="formInline" :materData="materData" :planToolList="toolList"></contentDetail>
        </Modal>
      </div>

      <!-- 第三步 -->
      <div v-if="current === 2" class="second" key="stepTwoValidate">
        <Form class="search-form" style="width: 100%;" ref="stepTwoValidate" :rules="ruleValidate" :model="formInline">
          <Row :gutter="24">
            <Col span="12">
            <FormItem label="点检级别" class="item " prop="planLevel">
              <Select v-model="formInline.planLevel" :placeholder="`${$t('common.selectInfo')}`">
                <Option value="一级点检" label="一级点检"></Option>
                <Option value="二级点检" label="二级点检"></Option>
                <Option value="三级点检" label="三级点检"></Option>
              </Select>
            </FormItem>
            </Col>
            <Col span="9">
            <FormItem label="触发条件" prop="planCycle">
              <InputNumber :min="1" style="width: 100%;" v-model="formInline.planCycle" :placeholder="`${$t('common.inputInfo')}`">
              </InputNumber>
            </FormItem>
            </Col>
            <Col span="3">
            <FormItem label="周期" prop="cycleUnit">
              <Select v-model="formInline.cycleUnit" :placeholder="`${$t('common.selectInfo')}`">
                <Option v-for="(item,index) in cycle" :key="index" :value="item.name" :label="item.name"></Option>
              </Select>
            </FormItem>
            </Col>
          </Row>
          <Row :gutter="24">
            <Col span="12">
            <FormItem label="首次生成时间" class="item " prop="firstTime">
              <DatePicker type="datetime" format="yyyy-MM-dd HH:mm:ss"
                :placeholder="`${$t('common.selectInfo')}`" :value="formInline.firstTime"
                @on-change="(val) => { formInline.firstTime = val }">
              </DatePicker>
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem label="计划截止时间" class="item " prop="endTime">
              <DatePicker type="datetime" format="yyyy-MM-dd HH:mm:ss"
                @on-change="(val) => { formInline.endTime = val }" :placeholder="`${$t('common.selectInfo')}`"
                :value="formInline.endTime"></DatePicker>
            </FormItem>
            </Col>
          </Row>

          <Row :gutter="24">
            <Col span="12">
             
            <FormItem label="标准工时(min)" prop="planWorkhours">
              <InputNumber style="width:100%;" disabled v-model="formInline.planWorkhours" :placeholder="`${$t('common.inputInfo')}`">
              </InputNumber>
            </FormItem>
            </Col>
            <Col span="9">
            <FormItem label="任务存活时间" class="item" prop="liveTimeD"
              :rules="{ required: true, message: '请输入任务存活时间', trigger: 'change', type: 'number' }">
              <InputNumber style="width: 90%;" v-model="formInline.liveTimeD" :placeholder="`${$t('common.inputInfo')}`">
              </InputNumber>
              <span style="margin-left: 10px;">天</span>
            </FormItem>
            </Col>
            <Col span="3">
            <FormItem label="小时" class="item" prop="liveTimeH"
              :rules="{ required: true, message: '请输入', trigger: 'change', type: 'number' }">
              <InputNumber style="width: 100%;" v-model="formInline.liveTimeH" :placeholder="`${$t('common.inputInfo')}`">
              </InputNumber>
              <!-- <span style="margin-left: 10px;">小时</span> -->
            </FormItem>
            </Col>
          </Row>
          <Row :gutter="24" class="mt16">
            <Col span="12">
            <FormItem :label="$t('是否自动分配')" class="item" prop="isAllot">
              <RadioGroup v-model="formInline.isAllot">
                <Radio label="0">{{ $t('common.Yes') }}</Radio>
                <Radio label="1">{{ $t('common.No') }}</Radio>
              </RadioGroup>
            </FormItem>
            </Col>
          </Row>

        </Form>
      </div>

      <div class="nextBtn">
        <!-- {{ current }} -->
        <Button @click="previous" v-if="current !== 0">{{ $t('common.Pre') }}</Button>
        <Button type="primary" @click="next" v-if="current !== 2">{{ $t('common.Next') }}</Button>
        <Button type="primary" :loading="loading" @click="create" v-if="current === 2">
          {{ $t('common.Creatingsuccessful') }}
        </Button>
      </div>
    </Card>


    <Drawer title="添加点检内容" :styles="styles" :scrollable="true" v-model="drawerVisible"
      width="1200" class="drawer">
      <div class="search">
				<Col span="24">
					<Row>
						<Col span="6" style="padding: 0 5px">
							<label>点检项目</label>
							<Input v-model="searchPlanParams.itemProject" clearable />
						</Col>
						<!-- <Col span="6" style="padding: 0 5px">
          <label>{{ $t('设备等级') }}</label>
          <Select v-model="searchPlanParams.categoryName" filterable @on-change="categorySelectChange" clearable
            :placeholder="`${$t('common.selectInfo')}`" class="select">
            <Option v-for="v in category" :value="v.value" :key="v.value" :label="v.label">
            </Option>
          </Select>
          </Col> -->
						<!-- <Col span="6" style="padding: 0 5px">
          <label>{{ $t('设备类别') }}</label>
          <Select v-model="searchPlanParams.deviceType" filterable clearable :placeholder="`${$t('common.selectInfo')}`">
            <Option v-for="(item, index) of deviceTypeList" :value="item.value" :key="index" :label="item.value" />
          </Select>
          </Col> -->
						<Col span="6" style="padding: 0 5px">
							<label>点检级别</label>
							<Select v-model="searchPlanParams.itemLevel" clearable :placeholder="`${$t('common.selectInfo')}`">
								<Option v-for="item of levelList" :value="item.key" :key="item.key" :label="item.name"> </Option>
							</Select>
						</Col>
						<Col span="6">
							<Button type="primary" class="ivu-btn-lg" @click="changePlanNum">{{ $t('common.Query') }}</Button>
						</Col>
					</Row>
				</Col>
				<Col span="24" style="padding-top: 10px">
					<!-- <Row>
          <div style="display: flex; align-items: center; justify-content: flex-start;">
            <Col span="6" style="padding: 0 5px">
            <label>{{ $t('保养周期') }}</label>
            <Select v-model="searchPlanParams.triggerCycle" filterable clearable
              :placeholder="`${$t('common.selectInfo')}`">
              <Option v-for="(item, index) of cycle" :value="item.key" :key="index" :label="item.name">
              </Option>
            </Select>
            </Col>
            <Col span="6" style="padding: 0 5px">
            <label>{{ $t('保养位置') }}</label>
            <Select filterable clearable class="select" v-model="searchPlanParams.bomId"
              :placeholder="`${$t('common.selectInfo')}`" @on-change="materielNoChangeBom"
              :remote-method="materielNoChange">
              <Option v-for="item in materielNoList" :value="item.id" :label="item.materielNo + '-' + item.materielName"
                :key="item.id" />
            </Select>
            </Col>

            <Col span="6" style="padding: 0 5px">
            <label>{{ $t('安装位置') }}</label>
            <Cascader :data="orgList" :transfer="true" v-model="orgCodeList" change-on-select
              @on-change="handleCasChange" />
            </Col>

            <Col span="6" style="padding: 0 5px">
            <label>{{ $t('equipCheck.SerialNo') }}</label>
            <Select v-model="searchPlanParams.deviceMId" filterable clearable
              :placeholder="`${$t('common.inputInfo')}${$t('equipCheck.SerialNo')}`" :remote-method="handleRemote">
              <Option v-for="item in deviceMIdList" :value="item.deviceMId" :label="item.desc" :key="item.deviceMId" />
            </Select>
            </Col>
          </div>
        </Row> -->
				</Col>
				<!-- <Col span="24" style="padding-top: 10px; display: flex; justify-content: center">
					<Button type="primary" class="ivu-btn-lg" @click="changePlanNum">{{ $t('common.Query') }}</Button>
				</Col> -->
			</div>
      <div class="tableContent" style="margin: 10px">
        <Table border class="resizable-table" @on-column-width-resize="onColumnWidthResize" ref="drawerSelection"
          :columns="drawerColumns" :data="drawerData" @on-selection-change="handleDrawerChange"></Table>
      </div>
      <div class="demo-drawer-footer">
        <Page :total="drawerTotal" :page-size="drawerpageSize" :page-size-opts="$variable.pageSizes"
          :current="drawerpageNum" @on-change="drawerchangePageNum" @on-page-size-change="drawerchangePageSize" show-sizer
          show-total />
        <div>
          <Button class="ivu-btn-lg" style="margin-right: 8px" @click="handleDrawerCancel">{{
            $t('common.Cancle')
          }}
          </Button>
          <Button class="ivu-btn-lg" type="primary" @click="handleDrawerOk">{{ $t('maintenance.Confirmed') }}</Button>
        </div>
      </div>
    </Drawer>
    <signle-common-modal ref="signleCommonModal" @handleRefresh="handleRefresh" />
  </div>
</template>

<script>
import recursion from '@/util/recursion'
import contentDetail from './contentDetail.vue'
// import util from '@/util/util'
import { mapGetters } from 'vuex'
import toggleTableOperation from "@/mixins/toggleTableOperation";
import signleCommonModal from "@/views/devScene/repair/modules/signleCommonModal";
export default {
  name: "addMaintainPlan",
  mixins: [toggleTableOperation],
  components: {
    contentDetail,
    signleCommonModal
  },
  props: ['mainDevice', 'factoryList', 'planPositionList', 'planClassifyList', 'editId'],
  data() {
    return {
      customCacheKey: "addMaintainPlanStep1",
      drawerTotal: 0,
      drawerpageSize: 10,
      drawerpageNum: 1,
      pageSizeOption: [10, 20, 30, 50,100,200,500],
      deviceMIdList: [],
      selectData: [],
      current: 0,
      visible: false,
      drawerVisible: false,
      loading: false,
      addDevVisible: false,
      disabledMinutes: [0, 10, 20],
      searchParams: {},
      searchPlanParams: {},
      styles: {
        height: 'calc(100% - 55px)',
        overflow: 'scroll',
        paddingBottom: '53px',
        position: 'static'
      },
      formInline: {
        planName: '',
        firstTime: this.$moment(new Date()).format('YYYY-MM-DD HH:00:00'),
        endTime: this.$moment(new Date()).format('YYYY-MM-DD HH:00:00'),
        liveTimeD: 0,
        liveTimeH: 0,
        planWorkhours:0,
        cycleUnit:'',
        planCycle:1,
      },
      stepOneRuleValidate: {
        categoryName: [
          { required: true, message: "请选择设备类别", trigger: "change" },
        ],
        planName: [
          { required: true, message: "请输入点检计划", trigger: "blur" },
        ],
      },
      ruleValidate: {
        planCycle: [
          { required: true, message: "请选择触发时间", trigger: "blur",type:"number" },
        ],
        isAllot: [
          { required: true, message: "请选择", trigger: "blur" },
        ],
        cycleUnit:[
          { required: true, message: "请选择周期", trigger: "change" },
        ],
        planLevel: [
          { required: true, message: "请选择点检级别" },
        ],
        isConfirm: [
          { required: true, message: "请选择是否需要" },
        ],
        firstTime: [
          { required: true, message: "请选择日期" },
        ],
        endTime: [
          { required: true, message: "请选择日期" },
        ],
        liveTimeD: [
          { required: true, type: 'number', message: "请输入天数", trigger: "blur" },
        ],
        liveTimeH: [{ required: true, type: 'number', message: "请输入小时", trigger: "blur" },],
      },
      columns: [
        // { type: "selection", width: 60, align: "center" },
        {
          type: 'index',
          width: 80,
          title: `${this.$t('common.index')}`,
          align: 'center',
          resizable: true,
          tooltip: true,
        },
        {
          title: '模具名称',
          key: "moldName",
          align: 'center',
          minWidth: 100,
          tooltip: true,
          resizable: true,
        },
        {
          title: '模具编号',
          key: "moldCode",
          align: 'center',
          minWidth: 100,
          resizable: true,
          tooltip: true,
        },
        {
          title: '模具型号',
          key: "moldModel",
          align: 'center',
          minWidth: 100,
          resizable: true,
          tooltip: true,
        },
        {
          title: '功能位置',
          key: "functionLocation",
          align: 'center',
          minWidth: 100,
          tooltip: true,
          resizable: true,
        },
        {
          title: `${this.$t('common.operation')}`,
          slot: "action",
          align: "center",
          minWidth: 100,
        },
      ],
      addDevcolumns: [
        {
          type: "selection",
          width: 60,
          align: "center"
        },
        {
          title: '模具名称',
          key: "moldName",
          align: 'center',
          minWidth: 100,
          tooltip: true,
          resizable: true,
        },
        {
          title: '模具编号',
          key: "moldCode",
          align: 'center',
          minWidth: 100,
          tooltip: true,
          resizable: true,
        },
        {
          title: '模具型号',
          key: "moldModel",
          align: 'center',
          minWidth: 100,
          tooltip: true,
          resizable: true,
        },
        {
          title: '功能位置',
          key: "functionLocation",
          align: 'center',
          minWidth: 100,
          tooltip: true,
          resizable: true,
        },
      ],
      addDevdata: [],
      data: [],
      confirmedName: "",
      confirmedBy: "",
      materialList: {},
      toolList: [],
      materData: [],
      drawerSelectionData: [],
      category: [
        { label: 'A', value: 'A' },
        { label: 'B', value: 'B' },
        { label: 'C', value: 'C' },
      ],
      companyList: this.factoryList,
      position: this.planPositionList,
      classification: this.planClassifyList,
      levelList: [
        { name: "一级点检", key: '1' },
        { name: "二级点检", key: '2' },
        { name: "三级点检", key: '3' },
      ],
      cycle: [
        { name: '小时', key: '8' },
        // { name: "班次", key: "7" },
        { name: '日', key: '1' },
      ],
      pageParams: {
        total: 64,
        pageSize: 10,
        pageNum: 1,
        pageSizeOption: [10, 20, 30, 40],
      },
      addDevpageParams: {
        total: 0,
        pageSize: 10,
        pageNum: 1,
        pageSizeOption: [50, 100, 150, 200],
      },
      contentColumns: [
        {
          type: 'index',
          width: 80,
          title: `${this.$t('common.index')}`,
          align: 'center'
        },
        {
          title: '点检项目',
          key: 'checkName',
          align: 'center',
          minWidth: 100,
          tooltip: true,
          resizable: true,
        },
        {
          title: '描述',
          key: 'checkDes',
          align: 'center',
          minWidth: 100,
          tooltip: true,
          resizable: true,
        },
        {
          title: `点检周期`,
          key: 'checkCycle',
          align: 'center',
          minWidth: 100,
          tooltip: true,
          resizable: true,
          render: (h, params) => {
            return h(
              "span",
              params.row.checkCycle + (params.row.cycleUnit || '')
            );
          },
        },
         {
          title:'点检级别',
          key: 'checkLevel',
          align: 'center',
          minWidth: 100,
          tooltip: true,
          resizable: true,
          render: (h, params) => {
            return h('span', this.levelList.find(item => item.key == params.row.checkLevel).name)
          }
        },
        {
          title: '标准工时（S）',
          key: "manHour",
          align: 'center',
          minWidth: 160,
          resizable: true,
          tooltip: true,
        },
        {
          title: `${this.$t('common.operation')}`,
          slot: 'action',
          minWidth: 200,
          align: 'center'
        },
      ],
      contentData: [],
      drawerColumns: [
        {
          type: 'selection',
          align: 'center',
          width: 60
        },
        {
          title: '点检项目',
          key: "checkName",
          minWidth: 100,
          align: "center",
          resizable: true, tooltip: true,
        },
        {
          title: '描述',
          key: "checkDes",
          minWidth: 180,
          align: "center",
          resizable: true, 
          tooltip: true,
        },
        {
          title: '点检级别',
          key: "checkLevel",
          align: 'center',
          minWidth: 100,
          resizable: true,
          tooltip: true,
          render: (h, params) => {
            return h('span', this.levelList.find(item => item.key == params.row.checkLevel).name)
          }
        },
        {
          title: '点检周期',
          key: "checkCycle",
          align: 'center',
          minWidth: 100,
          resizable: true,
          tooltip: true,
          render: (h, params) => {
            return h(
              "span",
              params.row.checkCycle + params.row.cycleUnit
            );
          },
        },
        {
          title: '标准工时（S）',
          key: "manHour",
          align: 'center',
          minWidth: 160,
          resizable: true,
          tooltip: true,
        },
        {
          title: '需求人数',
          key: "reqPNum",
          minWidth: 130,
          align: "center",
          resizable: true,
          tooltip: true,
        },
        {
          title: `${this.$t('是否上传sop')}`,
          key: "isCheckSop",
          align: 'center',
          minWidth: 200,
          resizable: true,
          tooltip: true,
        },
        // {
        //   title: '模具编号',
        //   key: "moldCode",
        //   minWidth: 160,
        //   align: "center",
        //   resizable: true,
        //   tooltip: true,
        // },
        // {
        //   title: '模具等级',
        //   key: "moldGrade",
        //   minWidth: 160,
        //   align: "center",
        //   resizable: true,
        //   tooltip: true,
        // },
        // {
        //   title: '模具名称',
        //   key: "moldName",
        //   align: 'center',
        //   minWidth: 160,
        //   resizable: true,
        //   tooltip: true,
        // },
        {
          title: `${this.$t('创建时间')}`,
          key: "createTime",
          minWidth: 200,
          align: "center",
          resizable: true,
          tooltip: true,
        },
      ],
      otherColumns: [
        {
          type: 'selection',
          align: 'center',
          width: 60
        },
        {
          title: `${this.$t('设备等级')}`,
          key: "categoryName",
          minWidth: 100,
          align: "center",
          resizable: true, tooltip: true,
        },
        {
          title: `${this.$t('设备类别')}`,
          key: "deviceType",
          minWidth: 180,
          align: "center",
          resizable: true, tooltip: true,
        },
        {
          title: `${this.$t('maintenance.EquipmentNo')}`,
          key: "deviceNo",
          align: 'center',
          minWidth: 100,
          resizable: true, tooltip: true,
        },
        {
          title: `${this.$t('设备名称')}`,
          key: "deviceName",
          align: 'center',
          minWidth: 100,
          resizable: true, tooltip: true,
        },
        {
          title: `${this.$t('设备流水号')}`,
          key: "deviceMId",
          minWidth: 130,
          align: "center",
          resizable: true, tooltip: true,
        },
      ],
      drawerData: [],
      deviceTypeList: [],
      deviceNameList: [],
      orgList: [],
      orgIdList: [],
      orgCodeList: [],
      materielNoList: [],
      deviceList: []
    };
  },
  computed: {
    ...mapGetters([
      'copyStatus'
    ]),
    // 'formInline.planWorkhours'() {
    //   const sum=this.contentData.manHours.reduce((prev, cur)=>{
    //       return prev + cur;
    //   });
    //   console.log(sum);
    //   return sum;
    // }
  },
  watch: {
    addDevVisible: function (val) {
      if (!val) {
        if (this.current == 1) {
          this.customCacheKey = 'addMaintainPlanStep2'
          this.getColumnWidth(this.contentColumns)
        }
        if (this.current == 0) {
          this.customCacheKey = 'addMaintainPlanStep1'
          this.getColumnWidth(this.columns)
        }
      }
    },
    drawerVisible: function (val) {
      if (!val) {
        if (this.current == 1) {
          this.customCacheKey = 'addMaintainPlanStep2'
          this.getColumnWidth(this.contentColumns)
        }
        if (this.current == 0) {
          this.customCacheKey = 'addMaintainPlanStep1'
          this.getColumnWidth(this.columns)
        }
      }
    },
  },
  created() {
    this.getColumnWidth(this.columns)

    if (this.editId) {
      this.getDetail(this.editId)
    }
    this.getOrgList()
  },
  mounted() {
    this.getFaultCategory("设备类型")
  },
  methods: {
    getDetail(id){
      const that=this;
      this.axios({
        url: '/dms/moldSpotCheckPlan/getMoldSpotCheckPlanById',
        method:'get',
        params: { id },
      }).then(res=>{
        that.getPlanDetail(res.data)
      })
    },
    chosePeople() {
      this.$refs.signleCommonModal.show({}, 'more', this.confirmedBy)
    },
    handleRefresh(userIds, userName) {
      this.confirmedName = userName.join(',')
      this.confirmedBy = userIds.join(',')
    },
    handleCasChangeOne(val, selectedData) {
      this.searchParams.orgId = val[val.length - 1]
      // this.formItem.orgName = selectedData[selectedData.length - 1].label
    },
    handleRemote(query) {
      if (!query) {
        return
      }
      const fn = this.debounceSerach(() => {
        let _query = query.split('-')
        if (Array.isArray(_query)) _query = _query[0]
        this.axios({
          method: "get",
          url: "/dms/dmsDevice/deviceList",
          params: {
            deviceMId: _query,
            deviceNo: '',
            assetsNo: "",
            orgCode: this.searchParams.orgCode || '',
          },
        }).then((res) => {
          if (res.code === 200) {
            this.deviceMIdList = res.data.map(item => {
              item.desc = item.deviceMId + '-' + item.deviceName + '-' + item.deviceNo
              return item;
            })
          } else {
            this.$Message.warning({
              content: res.msg,
              duration: 6,
              closable: true,
            });
          }
        })
      }, 300)
      fn()
    },
    handleCasChange(val) {
      this.searchPlanParams.orgCode = val[val.length - 1];
    },
    drawerchangePageNum(val) {
      this.drawerpageNum = val;
      this.searchPlanList();
    },
    drawerchangePageSize(pageSize) {
      this.drawerpageSize = pageSize;
      this.searchPlanList();
    },
    debounceSerach(fn, delay) {
      let _this = this
      return function f(...args) {
        if (_this.timeID) {
          clearTimeout(_this.timeID);
        }
        _this.timeID = setTimeout(() => {
          fn(args);
        }, delay);
      };
    },
    materielNoChange(val, value) {
      if (val && this.materielNoList.find(item => (item.materielNo + '-' + item.materielName) === val)) {
        return;
      }

      const fn = this.debounceSerach(() => {
        const params = {
          deviceType: this.searchPlanParams.deviceType,
          param: val
        }
        this.axios({
          method: 'post',
          // url: '/dms/applyUse/querySearch',
          url: '/dms/dmsBom/queryByDeviceTypeAndDeviceName',
          data: { ...params }
        }).then(res => {
          if (res.code === 200) {
            if (res.data) {
              this.materielNoList = res.data
            }
            if (value) {
              this.searchPlanParams.bomId = Number(value)
            }
          } else {
            this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
          }
        })
      }, 360)
      fn()
    },
    searchDevice(query) {
      let orgCode = "";
      if (this.searchParams.orgId) {
        orgCode = this.searchParams.orgId.at(-1)
      }

      this.axios({
        method: "get",
        url: "/dms/dmsDevice/deviceListByParams",
        params: {
          orgCode: orgCode,
          param: query,
          deviceType: this.formInline.deviceType,
          categoryName: this.formInline.categoryName
        },
      }).then((res) => {
        if (res.code === 200) {
          this.deviceList = res.data;
        }
      });
    },
    deviceTypeChange(val) {
      if (this.data && this.data.length) {
        this.data = []
      }
      if (this.contentData && this.contentData.length) {
        this.contentData = []
      }
      if (val) {
        this.formInline.deviceType = val
      }
    },
    //获取故障数据
    getFaultCategory(name) {
      this.axios({
        method: 'get',
        url: '/dms/faultCategory/basicDict',
        params: { name }
      }).then(res => {
        if (res.code === 200) {

          if (name === '故障分类') {
            this.faultCategoryList = res.data.map(item => {
              if (item.value) return item;
            })
          } else if (name === '设备类型') {
            this.deviceTypeList = res.data.map(item => {
              if (item.value) return item;
            })
          }
        } else {
          this.$Message.warning(({ content: res.msg, duration: 6, closable: true }))
        }
      })
    },
    planNamechange(val) {
      this.formInline.planName = JSON.parse(JSON.stringify(val.target.value))
      localStorage.setItem('planNameInfo', JSON.stringify(val.target.value))
    },
    levelChange() {
      if (this.contentData && this.contentData.length) {
        this.contentData = []
      }
    },
    deviceNameChange() {
      if (this.data && this.data.length) {
        this.data = []
      }
      if (this.contentData && this.contentData.length) {
        this.contentData = []
      }
    },
    categorySelectChange(categoryName) {
      if (this.data && this.data.length) {
        this.data = []
      }
      if (this.contentData && this.contentData.length) {
        this.contentData = []
      }
      if (categoryName) {
        return this.axios({
          method: 'get',
          url: '/dms/dcmMaintainItem/queryDeviceNames',
          params: {
            categoryName
          }
        }).then(res => {
          if (res.code == 200) {
            this.deviceNameList = res.data.map(val => ({
              label: val,
              value: val
            }))
          }
        })
      }
    },
    back() {
      this.$emit('handlePlanOk')
      // this.$emit("addMaintain", false);
    },
    getOrgList() {
      this.axios({
        method: 'get',
        url: '/basic/organization/findListByToken',
        params: {}
      }).then(res => {
        if (res.code === 200) {
          const obj = {
            label: 'name',
            value: 'code',
            children: 'children'
          }
          this.orgList = recursion.convertTree(res.data, obj)
        } else {
          this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
        }
      })
    },
    getPlanDetail(data) {
      const { mmoldSpotCheckPlanRefs, mmoldSpotCheckPlanSpotCheckRefs } = data
      this.formInline = {
        ...data,
      }
      this.contentData = mmoldSpotCheckPlanSpotCheckRefs.map(item => {
        return {
          id:item.id,
          checkId:item.checkId,
          checkCycle: item.checkCycle,
          checkLevel: item.checkLevel,
          checkName: item.checkName,
          manHour:item.manHour,
        }
      });
      this.data = mmoldSpotCheckPlanRefs.map(item => {
        return {
          id:item.id,
          moldId: item.moldId,
          moldCode: item.moldCode,
          moldName: item.moldName,
          moldModel: item.moldModel,
          functionLocation: item.functionLocation,
        }
      });
    },
    changePageSize(pageSize) {
      this.addDevpageParams.pageSize = pageSize;
      this.searchList();
    },
    changePageNum(val) {
      this.addDevpageParams.pageNum = val;
      this.searchList();
    },

    next() {
      if (this.current == 0) {
        this.customCacheKey = 'addMaintainPlanStep2'
        this.getColumnWidth(this.contentColumns)
        this.$refs["stepOneValidate"].validate((valid) => {
          if (valid) {
            if (!this.data.length) {
              this.$Message.warning(({ content: '请添加点检模具！', duration: 6, closable: true }));
              return false
            }
            // 注视代码为校验是否重名
            if (!this.editId || this.copyStatus) {
              this.current += 1;
            } else {
              this.current += 1;
            }
          } else {
            return;
          }
        });
      } else if (this.current == 1) {
        if (!this.contentData.length) {
          this.$Message.warning(({ content: '请添加点检内容！', duration: 6, closable: true }));
          return false
        }
        let sum=this.contentData.reduce((prev, cur)=>{
          console.log(prev.manHour,prev,cur,cur.manHour);
            return prev + cur.manHour;
        },0);
        console.log(sum,'sum');
        this.$set(this.formInline,'planWorkhours',sum)
        this.customCacheKey = 'addMaintainPlanStep2'
        this.getColumnWidth(this.contentColumns)

        // let hour = this.contentData.map(item => item.itemHours).reduce((pre, current) => Number(pre) + Number(current))
        // this.stepTwoValidate.itemHour = hour
        this.current += 1;
      } else {
        this.current += 1;
        this.customCacheKey = 'addMaintainPlanStep1'
        this.getColumnWidth(this.columns)
      }
    },
    previous() {
      this.current -= 1;
      if (this.current == 0) {
        this.customCacheKey = 'addMaintainPlanStep1'
        this.getColumnWidth(this.columns)
      }
      if (this.current == 0) {
        this.customCacheKey = 'addMaintainPlanStep2'
        this.getColumnWidth(this.contentColumns)
      }
    },
    create() {
      this.$refs.stepTwoValidate.validate((valid) => {
        if (valid) {
          const firstTimeinfo = new Date(this.formInline.firstTime).getTime()
          const nowTime = new Date().getTime()
          if (Number(firstTimeinfo) < Number(nowTime)) {
            this.$Message.warning(({
              content: '首次生成时间必须大于当前时间！',
              duration: 6,
              closable: true
            }));
            return
          }
          this.loading = true
          const planName = JSON.parse(localStorage.getItem('planNameInfo'))
          let data = {
            ...this.formInline,
            mmoldSpotCheckPlanRefs:this.data,
            mmoldSpotCheckPlanSpotCheckRefs:this.contentData,
          }
          if (planName) {
            data.planName = planName
          }
          if (!this.editId || this.copyStatus) {
            this.axios({
              method: 'post',
              url: '/dms/moldSpotCheckPlan/addMoldSpotCheckPlan',
              data
            }).then(res => {
              if (res.code === 200) {
                this.$emit('handlePlanOk')
                this.$Message.success(({ content: '新增点检计划成功！', duration: 2, closable: true }))
              } else {
                this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
              }
            }).finally(() => {
              this.loading = false
            })
          } else {
            // let params = {
            //   ...data,
            //   id: this.editId.id
            // }
            this.axios({
              method: 'post',
              url: '/dms/moldSpotCheckPlan/updateMoldSpotCheckPlan',
              data,
            }).then(res => {
              if (res.code === 200) {
                this.$emit('handlePlanOk')
                this.$Message.success(({ content: '编辑点检计划成功！', duration: 2, closable: true }))
              } else {
                this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
              }
            }).finally(() => {
              this.loading = false
            })
          }
        } else {
          // this.$Message.warning(({content: '请将信息填写完整！', duration: 6, closable: true}));
          return;
        }
      });


    },
    addDev() {

      this.customCacheKey = 'addMaintainPlanAddDevice'
      this.getColumnWidth(this.addDevcolumns)

      this.addDevcolumns.reverse().reverse()

      this.addDevVisible = true;
      this.$forceUpdate()
      // this.searchParams = {}
      this.searchList()
    },
    handleSelectionChange(selectionData) {
      let arr = selectionData.map(item=>{
        return {
          moldId: item.id,
          moldCode: item.moldCode,
          moldName: item.moldName,
          moldModel: item.moldModel,
          functionalLocationName: item.functionalLocationName,
          functionLocation: item.functionLocation,
        }
      })
      this.selectData = arr
    },
    addDevCancel() {
      this.addDevVisible = false
      this.$refs.devSelection.selectAll(false)
    },
    addDevOk() {
      if (this.data.length) {
        // let arr = this.data.filter(item => this.selectData.some(x => x.moldId == item.moldId))
        // // console.log(arr)
        // if (arr.length) {
        //   this.$Message.warning(({ content: '有重复数据，请重新选择！', duration: 6, closable: true }));
        //   return false
        // }
        this.addDevVisible = false
        this.data = this.concatArrAndOne(this.data, this.selectData,'moldId')

        this.$refs.devSelection.selectAll(false)
      } else {
        this.addDevVisible = false
        this.data = [...this.data, ...this.selectData]
        this.$refs.devSelection.selectAll(false)
      }

    },
    handleChangeDevice(value) {
      console.log(value)
      // this.searchList()
    },
    //分页
    changeNum() {
      this.addDevpageParams.pageNum = 1;
      this.searchList();
    },
    searchList() {
      let data = {
        ...this.searchParams,
        pageNum: this.addDevpageParams.pageNum,
        pageSize: this.addDevpageParams.pageSize,
				idList:this.data.map(item=>item.moldId)
      }
      if (data.functionalLocationName && data.functionalLocationName.length!=0) {
        data.functionalLocationName=[data.functionalLocationName.at(-1)]
      }
      this.axios({
        method: 'POST',
        url: '/dms/moldinfo/getDeviceTzList',
        data
      }).then(res => {

        if (res.code === 200) {
          this.addDevdata = res.data.records
          this.addDevpageParams.total = res.data.total
        } else {
          this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
        }
      })
    },
    changePlanNum() {
      this.searchPlanList();
    },
    searchPlanList() {
      let data = {
        pageNum: this.drawerpageNum,
        pageSize: this.drawerpageSize,
        checkName: this.searchPlanParams.itemProject,
				// deviceType: this.formInline.deviceType,
				checkLevel: this.searchPlanParams.itemLevel,
      };
      this.axios({
        method: 'POST',
        url: '/dms/moldSpotCheck/getMoldSpotCheckList',
        data
      }).then(res => {
        if (res.code === 200) {
          this.drawerData = res.data.records
          this.drawerTotal = res.data.total
        } else {
          this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
        }
      })
    },
    handleDrawerChange(data) {
      this.drawerSelectionData=data.map(item => {
        return {
          checkId:item.id,
          checkName:item.checkName,
          checkDes:item.checkDes,
          checkCycle:item.checkCycle,
          checkLevel:item.checkLevel,
          manHour:item.manHour,
        }
      })
    },
    addPlan() {
      this.customCacheKey = 'addMaintainPlanAddPlan'
      this.getColumnWidth(this.drawerColumns)

      this.drawerColumns.reverse().reverse()
      this.searchPlanParams = {}
      this.drawerVisible = true
      this.searchPlanList()
    },
    handleDrawerCancel() {
      this.drawerVisible = false
      this.$refs.drawerSelection.selectAll(false)
    },
    handleDrawerOk() {
      if (this.contentData.length) {
        // let arr = this.contentData.filter(item => this.drawerSelectionData.some(x => x.id == item.id))
        // if (arr.length) {
        //   this.$Message.warning(({ content: '有重复数据，请重新选择！', duration: 6, closable: true }));
        //   return false
        // }
        this.drawerVisible = false
        this.contentData = this.concatArrAndOne(this.contentData, this.drawerSelectionData,'id')

        // this.contentData = [...this.contentData, ...this.drawerSelectionData]
        this.$refs.drawerSelection.selectAll(false)
      } else {
        this.drawerVisible = false
        this.contentData = [...this.contentData, ...this.drawerSelectionData]
        this.$refs.drawerSelection.selectAll(false)
      }
    },
    seeDetail(row) {
      this.visible = true
      this.getWlDetail(row.itemId || row.id)
    },
    getWlDetail(itemId) {
      this.axios({
        method: 'get',
        url: '/dms/dcmMaintainItem/queryById',
        params: {
          id: itemId
        }
      }).then(res => {
        if (res.code === 200) {
          this.formInline = {
            ...res.data,
            planName: this.formInline.planName,
            triggerCycle: res.data.triggerCycle ? res.data.triggerCycle.split(',') : [],
          }
          if (this.formInline.planLevel) {
            this.formInline.planLevel = this.levelList.find(val => val.key === this.formInline.planLevel).name
          }
          this.toolList = res.data.dcmMaintainToolList.map(item => {
            return {
              ...item,
              isEdit: false,
            }
          })
          this.materData = res.data.dcmMaintainMaterialList.map(item => {
            return {
              ...item,
              isEdit: false,
            }
          })
        } else {
          this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
        }
      })
    },
    deleteRow(row) {
      this.contentData = this.contentData.filter(item => item.checkId != row.checkId)
    },
    deleteDevRow(row) {
      this.data = this.data.filter(item => item.moldId != row.moldId)
    },
  },
};
</script>

<style lang="scss">
.addMaintainPlan {
  background: #fff;

  .line-title {
    display: flex;
    justify-content: flex-start;
    font-size: 20px;
    padding: 10px;
    //border-bottom: 1px solid #dddddd;
    align-items: center;
    position: absolute;
    top: 3px;
    right: 0;

    .ivu-steps .ivu-steps-head,
    .ivu-steps-item.ivu-steps-status-process .ivu-steps-title {
      background: transparent;
    }

    .ivu-steps .ivu-steps-title {
      background: transparent;
      vertical-align: sub;
    }

    .back {
      color: #187bdb;
      font-size: 16px;
      padding-left: 20px;
      cursor: pointer;
    }

    .steps {
      width: 400px;
      margin-left: auto;
    }
  }

  .searchBox {
    .addDev {
      font-size: 16px;
      padding: 20px 0 0 10px;
    }

    .labelTop {
      display: flex;
      /*justify-content: space-between;*/
      border-bottom: 2px solid #d7d7d7;

      .item {
        width: 27%;
        margin: 0 10px 20px 10px;
      }
    }

    .label {
      display: flex;

      .item {
        margin-left: 10px;
      }
    }
  }

  .nextBtn {
    text-align: center;
    padding: 50px 0px;

    button {
      margin: 10px;
    }
  }
}

.second {
  .search-form {
    width: 30%;
  }
}

.third {
  .addPlan {
    font-size: 16px;
    padding: 20px 0 20px 10px;
  }
}

.addDevModal {
  .search-form {
    padding: 0;

    .label {
      display: flex;
    }
  }
}

.drawer {
  .search {
    display: flex;
    align-items: center;
    flex-wrap: wrap;

    button {
      margin: 20px 0 0 15px;
    }
  }

  .demo-drawer-footer {
    width: 100%;
    position: absolute;
    bottom: 0;
    left: 0;
    padding: 0 30px 15px 30px;
    //text-align: right;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #fff;
  }
}
</style>
